/**
 * 
 */
package com.pocketsweet.service;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.widget.ImageView;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.RefreshCallback;
import com.avos.avoscloud.SignUpCallback;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.pocketsweet.MLCache;
import com.pocketsweet.MLContext;
import com.pocketsweet.model.MLUser;
import com.pocketsweet.utils.PhotoUtil;
import com.pocketsweet.utils.StringUtils;

/**
 * @author hantian
 * 
 */
public class UserService {

	private static UserService _self;
	private static MLUser currentUser;

	public static ImageLoader imageLoader = ImageLoader.getInstance();

	public UserService() {

	}

	public static void init() {
		_self = new UserService();
	}

	public static MLUser getCurrentUser() {
		currentUser = MLUser.getCurrentUser(MLUser.class);
		return currentUser;
	}

	public static String getCurrentUserId() {
		MLUser user = getCurrentUser();
		
		if (user != null) {
			return user.getObjectId();
		} else {
			return MLContext.getUserLogin("userId") == null ? null : MLContext
					.getUserLogin("userId");
		}
	}

	/**
	 * 添加关注
	 * 
	 * @param userId
	 */
	public static void followUser(String userId) {
		UserService.getCurrentUser().followInBackground(userId, null);
	}

	/**
	 * 移除关注
	 * 
	 * @param userId
	 */
	public static void removeFollowUser(String userId) {
		UserService.getCurrentUser().unfollowInBackground(userId, null);
	}

	/**
	 * 
	 * @param account
	 * @param password
	 * @return
	 * @throws AVException
	 */
	public static void signUp(String account, String password, String mobile,
			SignUpCallback callback) throws AVException {
		MLUser user = new MLUser();
		user.setUsername(account);
		user.setPassword(password);
		user.setMobilePhoneNumber(mobile);
		user.signUpInBackground(callback);
	}

	/**
	 * 显示圆形头像
	 * 
	 * @param imageUrl
	 * @param avatarView
	 */
	public static void displayAvatar(String imageUrl, ImageView avatarView) {
		imageLoader.displayImage(imageUrl, avatarView,
				PhotoUtil.avatarImageOptions);
	}

	/**
	 * 显示方形头像
	 * 
	 * @param imageUrl
	 * @param squareView
	 */
	public static void displaySquare(String imageUrl, ImageView avatarView) {
		imageLoader.displayImage(imageUrl, avatarView,
				PhotoUtil.squareImageOptions);
	}

	/**
	 * 显示普通
	 * 
	 * @param imageUrl
	 * @param avatarView
	 */
	public static void displayImage(String imageUrl, ImageView avatarView) {
		imageLoader.displayImage(imageUrl, avatarView,
				PhotoUtil.normalImageOptions);
	}

	/**
	 * 显示Drawable背景图片
	 * 
	 * @param imageUrl
	 * @param avatarView
	 */
	public static void displayDrawableImage(int drawable, ImageView avatarView) {
		String imageUri = "drawable://" + drawable;
		imageLoader
				.displayImage(imageUri, avatarView, PhotoUtil.bgImageOptions);
	}

	/**
	 * 显示闪屏背景图片
	 * 
	 * @param imageUrl
	 * @param avatarView
	 */
	public static void displaySplashImage(int drawable, ImageView avatarView) {
		String imageUri = "drawable://" + drawable;
		imageLoader.displayImage(imageUri, avatarView,
				PhotoUtil.splashImageOptions);
	}

	/**
	 * 显示圆角icon
	 * 
	 * @param imageUrl
	 * @param avatarView
	 */
	public static void displayRoundDrawable(int drawable, ImageView avatarView) {
		String imageUri = "drawable://" + drawable;
		imageLoader.displayImage(imageUri, avatarView,
				PhotoUtil.squareRoundImageOptions);
	}

	/**
	 * 显示大图
	 * 
	 * @param imageUrl
	 * @param avatarView
	 */
	public static void displayBigImage(String imageUrl, ImageView avatarView) {
		imageLoader.displayImage(imageUrl, avatarView,
				PhotoUtil.bigImageOptions);
	}

	/**
	 * 显示背景
	 * 
	 * @param imageUrl
	 * @param avatarView
	 */
	public static void displayBgImage(String imageUrl, ImageView avatarView) {
		imageLoader
				.displayImage(imageUrl, avatarView, PhotoUtil.bgImageOptions);
	}

	/**
	 * 显示方形推荐
	 * 
	 * @param imageUrl
	 * @param squareView
	 */
	public static void displaySquareRecommend(String imageUrl,
			ImageView avatarView) {
		imageLoader.displayImage(imageUrl, avatarView,
				PhotoUtil.squareRecommendImageOptions);
	}

	/**
	 * 显示圆角图片
	 * 
	 * @param imageUrl
	 * @param squareView
	 */
	public static void displayRound(String imageUrl, ImageView avatarView) {
		imageLoader.displayImage(imageUrl, avatarView,
				PhotoUtil.squareImageOptions);
	}

	/**
	 * 异步线程更新img
	 * 
	 * @param imageUrl
	 * @param avatarView
	 */
	public static void setImageViewFromUrl(final String url,
			final ImageView imageView) {
		final HashMap<String, SoftReference<Drawable>> singleImageCache = new HashMap<String, SoftReference<Drawable>>();
		final Handler handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				imageView.setImageDrawable((Drawable) msg.obj);
			}
		};
		// 子线程不能更新UI,又不然会报错
		new Thread() {
			public void run() {
				Drawable drawable = loadImageFromUrl(url);
				if (drawable == null) {
					// Log.e("single imageview",
					// "single imageview of drawable is null");
				} else {
					// 把已经读取到的图片放入软引用
					singleImageCache.put(url, new SoftReference<Drawable>(
							drawable));
				}
				Message message = handler.obtainMessage(0, drawable);
				handler.sendMessage(message);
			};
		}.start();

	}

	/**
	 * 通过图片地址,返回drawable
	 * 
	 * @param url
	 * @return
	 */
	public static Drawable loadImageFromUrl(String url) {
		ByteArrayOutputStream out = null;
		Drawable drawable = null;
		int BUFFER_SIZE = 1024 * 16;
		InputStream inputStream = null;
		try {
			inputStream = new URL(url).openStream();
			BufferedInputStream in = new BufferedInputStream(inputStream,
					BUFFER_SIZE);
			out = new ByteArrayOutputStream(BUFFER_SIZE);
			int length = 0;
			byte[] tem = new byte[BUFFER_SIZE];
			length = in.read(tem);
			while (length != -1) {
				out.write(tem, 0, length);
				length = in.read(tem);
			}
			in.close();
			drawable = Drawable.createFromStream(
					new ByteArrayInputStream(out.toByteArray()), "src");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (Exception e) {
				}
			}
		}
		return drawable;
	}

	/**
	 * 获取用户User usr关注的人
	 * 
	 * @param usr
	 *            用户对象
	 * @return
	 * @throws AVException
	 */
	public static List<MLUser> findFollowee(MLUser usr) throws AVException {
		AVQuery<MLUser> followeeQuery = MLUser.followeeQuery(usr.getObjectId(),
				MLUser.class);
		return followeeQuery.find();
	}

	/**
	 * 查询用户资料完整度
	 * 
	 * @return
	 */
	public static int getUserProfileIntegrity(int photonum) {
		MLUser user = getCurrentUser();
		int score = 100;
		// // 头像
		// if (TextUtils.isEmpty(user.getAvatarUrl())) {
		// score -= 4;
		// }
		// 昵称
		if (TextUtils.isEmpty(user.getNickname())) {
			score -= 5;
		}
		// // 性别
		// if (TextUtils.isEmpty("" + user.getGender())) {
		// score -= 5;
		// }
		// 年龄
		if (TextUtils.isEmpty("" + user.getAgeNum())) {
			score -= 5;
		}
		// 城市
		if (TextUtils.isEmpty("" + user.getLocationCity())) {
			score -= 5;
		}
		// 签名
		if (TextUtils.isEmpty(user.getIntro())) {
			score -= 5;
		}
		// 外貌
		if (String.valueOf(user.getHeight()).equals("0")
				&& String.valueOf(user.getWeight()).equals("0")
				&& StringUtils.isEmpty(user.getFigure())) {
			score -= 5;
		}
		// 职业
		if (TextUtils.isEmpty(user.getJob())) {
			score -= 5;
		}
		// 喜欢的
		if (user.getLikeTags() == null || user.getLikeTags().size() == 0) {
			score -= 5;
		}
		// 特技
		if (user.getSpecial() == null || user.getSpecial().size() == 0) {
			score -= 5;
		}
		// 语言
		if (user.getLanguage() == null || user.getLanguage().size() == 0) {
			score -= 5;
		}
		// 照片
		score -= (8 - photonum) * 5;
		// 我属于
		if (StringUtils.isEmpty(user.getBelong())) {
			score -= 5;
		}
		// // 我中意
		// if (StringUtils.isEmpty(user.getLike())) {
		// score -= 5;
		// }
		// // 希望你
		// if (user.getWillingTags() == null || user.getWillingTags().size() ==
		// 0) {
		// score -= 5;
		// }
		// 想你叫我
		if (user.getCalledTags() == null || user.getCalledTags().size() == 0) {
			score -= 5;
		}
		// // 我想叫你
		// if (user.getCallTags() == null || user.getCallTags().size() == 0) {
		// score -= 5;
		// }
		// 声线
		if (!user.getIsHasVoice()) {
			score -= 5;
		}
		if (score > 100) {
			score = 100;
		}
		return score;
	}
}
